package com.qg.lizhanqi.videosquare.activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.melnykov.fab.FloatingActionButton;
import com.qg.lizhanqi.videosquare.fragment.HomeFragment;
import com.qg.lizhanqi.videosquare.fragment.MyFragment;
import com.qg.lizhanqi.videosquare.uitlhelp.MyUtils;
import com.qg.lizhanqi.videosquare.R;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;
import com.yolanda.nohttp.rest.Response;
import com.yolanda.nohttp.rest.SimpleResponseListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private    final String LOGININFO = "loginInfo";
    private final String URL = "http://101.200.142.201:8080/VideoPlay/login?";
    private final String UPLOADURL = "http://101.200.142.201:8080/VideoPlay/uploadVideo?";
    private static final String TAG = "李站旗MainActivity类";
    private Button btn_home;
    private FloatingActionButton floatingActionButton;
    private Button btn_my;
    private PopupWindow myPopWindow;
    private View myPopView;
    private View activity_main;
    private View loginView;
    private AlertDialog builder;
    private FrameLayout frameLayout;
    private SharedPreferences sharedPreferences;
    private EditText editText_login_phone;
    private EditText editText_login_pass;
    private Button btn_login_submit;
    private TextView tv_login_register;
    private RequestQueue requestQueues;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        //第一步：创建Nohttp请求对列
        requestQueues = NoHttp.newRequestQueue();
    }
    private void initView() {
        frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
        //设置默认的界面是首页
        getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, new HomeFragment()).commit();
        btn_home = (Button) findViewById(R.id.btn_home);
        floatingActionButton = (FloatingActionButton) findViewById(R.id.floatingActionButton);
        btn_my = (Button) findViewById(R.id.btn_my);
        btn_home.setOnClickListener(this);
        floatingActionButton.setOnClickListener(this);
        btn_my.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_home:
                getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, new HomeFragment()).commit();
                break;
            case R.id.floatingActionButton:
                    startActivityForResult(new Intent(this,VideoRecorderActivity.class),696);
                break;
            case R.id.btn_my:
                if (isLogin()) {
                    getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, new MyFragment()).commit();
                } else {//未登录
                    alterMyPop();
                }
                break;
            case R.id.btn_login_pop:
                if (myPopWindow.isShowing()) {
                    myPopWindow.dismiss();
                    alterLoginDiarlog();
                }
                break;
            case R.id.btn_my_pop:
                if (myPopWindow.isShowing()) {
                    myPopWindow.dismiss();
                    if (isLogin()) {
                        getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, new MyFragment()).commit();
                    } else {//未登录
                        Toast.makeText(MainActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.btn_login_submit:
                login();
                break;
            case R.id.tv_login_register:
                startActivity(new Intent(this, RegisterActivity.class));
                break;
        }
    }
    /*登录方法*/
    private void login() {
        String loginphone = editText_login_phone.getText().toString();
        String loginpass = editText_login_pass.getText().toString();
        if (TextUtils.isEmpty(loginphone)) {
            Toast.makeText(MainActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(loginpass)) {
            Toast.makeText(MainActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (MyUtils.isuserPhoneNumber(loginpass)) {
            Toast.makeText(MainActivity.this, "手机号格式错误！请检查", Toast.LENGTH_SHORT).show();
            return;
        }
        requsetJson(loginphone, loginpass);
    }
    /*使用notthp的Post请求*/
    private void requsetJson(String loginphone, String loginpass) {
        Log.i(TAG, "登陆用户: " + loginphone + "密码:" + loginpass);
        Request<JSONObject> jsonObjectRequest = NoHttp.createJsonObjectRequest(URL, RequestMethod.POST);
        jsonObjectRequest.add("userPhone", loginphone);
        jsonObjectRequest.add("userPassword", loginpass);
        requestQueues.add(2, jsonObjectRequest, new SimpleResponseListener<JSONObject>() {
            @Override
            public void onSucceed(int i, Response<JSONObject> response) {
                try {
                Log.i(TAG, "onSucceed: " + response.responseMesage());//ok
                JSONObject jsonObject = response.get();
                Log.i(TAG, "onSucceed: 登陆成功"+jsonObject.toString());
                    result(jsonObject.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
                Toast.makeText(MainActivity.this, "onFailed：登陆失败请稍后再试", Toast.LENGTH_SHORT).show();
            }
        });
    }
    /*登陆结果*/
    public void result(String responseString){
        try {
            JSONObject responseJson = new JSONObject(responseString);
            String code = responseJson.getString("code");
            if(code.equals("00000")){
                 /*关闭窗口*/
                if (builder.isShowing()) {
                    builder.dismiss();
                }
                JSONObject userinfo = responseJson.getJSONObject("userinfo");
                String userid = userinfo.getString("userid");
                String username = userinfo.getString("username");
                String userphone = userinfo.getString("userphone");
                if (sharedPreferences == null) {
                    sharedPreferences = getSharedPreferences(LOGININFO, Context.MODE_PRIVATE);
                }
                /*保存登陆状态*/
                sharedPreferences.edit()
                        .putBoolean("islogin",true)
                        .putString("userid",userid)
                        .putString("username",username)
                        .putString("userphone",userphone)
                        .commit();
                getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, new HomeFragment()).commit();
                Toast.makeText(MainActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
            }else if(code.equals("00010")){
                Toast.makeText(MainActivity.this, "登陆失败！账号已存在", Toast.LENGTH_SHORT).show();
            }
            else if(code.equals("00020")){
                Toast.makeText(MainActivity.this, "登陆失败！手机验证失败", Toast.LENGTH_SHORT).show();
            }
            else if(code.equals("00030")){
                Toast.makeText(MainActivity.this, "登陆失败！请求方式错误", Toast.LENGTH_SHORT).show();
            }
            else if(code.equals("00040")){
                Toast.makeText(MainActivity.this, "登陆失败！参数不能为空", Toast.LENGTH_SHORT).show();
            }
            else if(code.equals("00050")){
                Toast.makeText(MainActivity.this, "登陆失败！账户密码错误！", Toast.LENGTH_SHORT).show();
            }
            else if(code.equals("00060")){
                Toast.makeText(MainActivity.this, "登陆失败！Token过期！", Toast.LENGTH_SHORT).show();
            }
            else if(code.equals("00070")){
                Toast.makeText(MainActivity.this, "登陆失败！未知的错误！", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    /*登录窗口*/
    public void alterLoginDiarlog() {
        if (loginView == null) {
            Log.i(TAG, "alterLoginDiarlog: 填充登陆窗口");
            loginView = View.inflate(this, R.layout.activity_login, null);
            logininitView();
        }
        if (builder == null) {
            Log.i(TAG, "alterLoginDiarlog: 创建登陆窗口");
            builder = new AlertDialog.Builder(this).create();
            builder.setView(loginView);
        }
        builder.show();
    }
    private void logininitView() {
        editText_login_phone = (EditText) loginView.findViewById(R.id.editText_login_phone);
        editText_login_pass = (EditText) loginView.findViewById(R.id.editText_login_pass);
        btn_login_submit = (Button) loginView.findViewById(R.id.btn_login_submit);
        tv_login_register = (TextView) loginView.findViewById(R.id.tv_login_register);
        tv_login_register.setOnClickListener(this);
        btn_login_submit.setOnClickListener(this);
    }
    /*我的弹窗*/
    public void alterMyPop() {
        if (myPopView == null) {
            myPopView = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_register_or_login, null);
            activity_main = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
            Log.i(TAG, "alterMyPop: 填充view...");
        }
        if (myPopWindow == null) {
            myPopWindow = new PopupWindow(myPopView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            Log.i(TAG, "alterMyPop: 创建窗口...");
        }
        if (!myPopWindow.isShowing()) {
            Log.i(TAG, "alterMyPop: 展示窗口...");
            myPopWindow.showAsDropDown(activity_main);
        }
        myPopView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myPopWindow.isShowing()) {
                    Log.i(TAG, "alterMyPop: 关闭弹窗...");
                    myPopWindow.dismiss();
                }
            }
        });
        Button btn_login_pop = (Button) myPopView.findViewById(R.id.btn_login_pop);
        Button btn_my_pop = (Button) myPopView.findViewById(R.id.btn_my_pop);
        btn_my_pop.setOnClickListener(this);
        btn_login_pop.setOnClickListener(this);
    }
    /*判断是否登录过*/
    public  boolean isLogin() {
        if (sharedPreferences == null) {
            sharedPreferences =getSharedPreferences(LOGININFO, Context.MODE_PRIVATE);
        }
        boolean islogin = sharedPreferences.getBoolean("islogin", false);
        return islogin;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==969){
            String videoPath = data.getStringExtra("videoPath");
            Log.i(TAG, "onActivityResult: 返回路径："+videoPath);
            //获取userid
            String userid = this.getSharedPreferences(LOGININFO, Context.MODE_PRIVATE).getString("userid", null);
            if (userid != null) {
                //上传
                xUtilsUpLoadFile(UPLOADURL,userid,videoPath);
            }else {
                Toast.makeText(this, "请先登录后再上传", Toast.LENGTH_SHORT).show();
            }
        }
    }
    /*
        这里是 xUtils的文件post上传，
        url是上传到网络的位置
        userid是其他的参数
        filePath是要上传的文件位置
     */
    public  void  xUtilsUpLoadFile(String url,String userid,String filePath){
        //RequestParams对象是用来存放请求参数的
        RequestParams params = new RequestParams();
        params.addBodyParameter("userid",userid);//这里是一般的参数
        params.addBodyParameter("file",new File(filePath));//这里才是重点上传文件的参数
        //HttpUtils网络请求
        HttpUtils http = new HttpUtils();
        //发送请求
        /**
         * 第一个参数：请求方式
         *第二个参数：请求地址
         *第三个参数：请求携带的参数类
         *第四个参数：网络请求的监听
         */
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.i(TAG, "onSucceed:上传结果 "+responseInfo.result);
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(responseInfo.result);
                String code = jsonObject.getString("code");
                if (code.equals("00000")){
                    Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                    //刷新页面
                    //getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, new HomeFragment()).commit();
                }else {
                    Toast.makeText(MainActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(MainActivity.this, "网络问题！上传失败", Toast.LENGTH_SHORT).show();
                Log.i(TAG, "onFailure: 上传失败"+e.toString());
            }
        });
    }
}
